#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Ищет файлы форматов djvu, pdf и создает md5 хэш
'''
# TODO: поиск файлов по расширению:
#
# import fnmatch
#
# fileList = []
# ext = '*.djvu'
# 
# rootdir = '/home/max/books'
# for root, subFolders, files in os.walk(rootdir):
#     for file in files:
#         if fnmatch.fnmatch(file, ext):
#             fileList.append(os.path.join(root,file))
# print fileList

import os
import sys
import md5
import fnmatch
import Tkinter
import tkFileDialog

class FindApp:
    '''
    '''
    def __init__(self, win):
	self.root = win

	self.rootdir = '.' 
	self.file_list = [] # файлы
	self.md5sum = []    # md5

	self.init_widgets()
	pass

    def init_widgets(self):
	font = {}
	font['label']  = ("Helvetica", 16, "bold")
	font['entry']  = ("Times", 12, "bold")
	font['button'] = ("Helvetica", 13)

	self.frame = Tkinter.Frame(self.root, height=100, width=200)
	self.frame.grid()

	self.label = {}
	self.label['label'] = Tkinter.Label(self.frame)
	self.label['label']['text'] = u'1. Найти файлы'
	self.label['label'].pack()

	self.button = {}

	self.button['find'] = Tkinter.Button(self.frame)
        self.button['find']['text'] = u'Найти'
	self.button['find']['font'] = font['button']
        self.button['find'].bind('<Button>', self.find)
	self.button['find'].pack(fill=Tkinter.BOTH, expand=1)

        self.button['save'] = Tkinter.Button(self.frame)
        self.button['save']['text'] = u'Сохранить'
	self.button['save']['font'] = font['button']
        self.button['save'].bind('<Button>', self.save)
	self.button['save'].pack(fill=Tkinter.BOTH, expand=1)


	self.button['quit'] = Tkinter.Button(self.frame)
        self.button['quit']["text"] = u"Выход"
	self.button['quit']['font'] = font['button']
        self.button['quit'].bind('<Button>', self.quit)
	self.button['quit'].pack(fill=Tkinter.BOTH, expand=1)

    def md5sum(self, file):
	'''
	Вычисляет md5 сумму для файла file
	'''
	if os.path.isfile(file):
	    sum = md5.new(open(file, 'rb').read()).hexdigest()
	    return sum
	else:
	    return None

    def save(self, event):
	'''
	Сохраняем результат
	'''
	fname = None
	fname = tkFileDialog.asksaveasfilename(parent=self.root, filetypes=[('Data', '*.gz')] ,title="Сохранить как ...")
	if fname:
	    print fname
	    import gzip
	    #out = open(fname, 'w') 
	    out = gzip.GzipFile(fname, 'w', 9)
	    for i in xrange(len(self.file_list)):
		out.write('%s : %s\n' % (self.file_list[i], self.md5sum[i]))
	    out.close()
	self.label['label']['text'] = u'3. Выход.'

	
    def find(self, event):
	''' Рекурсивный поиск файлов с расширением *.pdf, *.djvu '''
	self.rootdir = tkFileDialog.askdirectory(parent=self.root, initialdir='.', title=u'Укажите папку с книгами')
	if len(self.rootdir) > 0:
	    print self.rootdir 
	    # расширения
	    extension = ['*.pdf', '*.PDF', '*.djvu', '*.djv', '*.DJVU', '*.DJV' ]
	    self.label['label']['text'] = u'Поиск...'
	    for root, subFolders, files in os.walk(self.rootdir):
		for file in files:
		    for ext in extension:
			if fnmatch.fnmatch(file, ext):
			    file_path = os.path.join(root, file)
			    self.file_list.append(file_path)
			    #print file_path
			    md5sum = md5.new(open(file_path, 'rb').read()).hexdigest()
			    #print md5sum
			    self.md5sum.append(md5sum)
	self.label['label']['text'] = u'2. Сохранить.'

    def quit(self, event):
	sys.exit(0)


win = Tkinter.Tk()
win.title(u'Поиск файлов электронных книг')
find = FindApp(win)
win.mainloop()
